# Create your views here.

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from models import Fund
from models import FundNetValue
from datetime import datetime
from google.appengine.ext import db
from google.appengine.api import mail
from BeautifulSoup import BeautifulSoup
import urllib2
import logging


def query(request):			
	fundList = genFundData()
	return render_to_response('fundata/query.html',{'funds':fundList})

def genFundData():
	funds = Fund.all()
	fundList = []	
	for f in funds:
		fundData = {}
		fundList.append(fundData)
		fundData['fundObj'] = f
		query = db.GqlQuery("SELECT * FROM FundNetValue WHERE fund = :fund ORDER BY date DESC",fund=f)
		result = query.fetch(2)
		lastNetValue = None
		preNetValue = None
		if result:
			lastNetValue = result[0]			
			fundData['lastNetValue'] = lastNetValue.netValue
			fundData['lastNetDate'] = lastNetValue.date
			fundData['lastUpdated'] = lastNetValue.lastUpdated
		if len(result) == 2:
			preNetValue = result[1]
			fundData['preNetValue'] = preNetValue.netValue
			fundData['preNetDate'] = preNetValue.date
		if lastNetValue <> None and preNetValue <> None:			
			fundData['diffValue'] = ((lastNetValue.netValue - preNetValue.netValue)/preNetValue.netValue)*100			
			fundData['currentAmount'] = round(f.buyCount * lastNetValue.netValue * f.exchangeRate) 
			fundData['charge'] = f.surcharge * f.amount
			fundData['profit'] = fundData['currentAmount'] - f.amount
			fundData['return'] = (fundData['profit'] / f.amount) * 100
			if (f.stopProfit*100) < fundData['return']:
				fundData['strategy'] = 'Sell'
			else:
				fundData['strategy'] = 'InSpect'		
	return fundList		
	
def show(request,fund_id):
	fund = Fund.get(fund_id)
	return render_to_response('fundata/show.html',{'fund':fund})

def updateNetValue(request):
	funds = Fund.all()	
	for f in funds:		
		logging.debug("start fetch url:" + f.dataSourceUrl)
		resp = urllib2.urlopen(f.dataSourceUrl)
		logging.debug("finish fetch url:" + f.dataSourceUrl)		
		parsingFundData(resp,f)
	fundlist = genFundData()
	for fd in fundlist:
		fund = fd['fundObj']		
		profit = fund.stopProfit * 100
		loss = (fund.stopLoss + 0.02) * 100
		if fd.has_key('return') and fd['return'] >= profit:
			notifyProfit(fund,fd)
		if fd.has_key('return') and fd['return'] <= loss:
			notifyLoss(fund,fd)
	return HttpResponseRedirect('/fundata/query')	

def parsingFundData(content,f):
	logging.debug("start parse content for fund:" + f.name)
	soup = BeautifulSoup(content)
	netvalueStr = soup.find("td",{"class":"t3n0c1"}).text
	netvalueStr = netvalueStr.replace('/','-')	
	netvalueDate = datetime.strptime(netvalueStr,"%Y-%m-%d").date()
	query = db.GqlQuery("SELECT * FROM FundNetValue WHERE fund = :fund AND date = DATE(:d)",fund=f,d=netvalueStr	)
	result = query.get()
	if not result:
		netvalue = float(soup.find("td",{"class":"t3n1"}).text)
		fundnetValue = FundNetValue(fund=f,netValue=netvalue,date=netvalueDate)
		fundnetValue.put()
		logging.debug("update netvalue for fund:" + f.name)
	logging.debug("finish parse content for fund:" + f.name)	

def notifyProfit(fund,fd):
	profit = fund.stopProfit * 100
	subject = fund.name + " has reach Stop Profit"
	mailto = "rock.chiu@gmail.com"
	content = fund.name + " Stop Profit Rate:" + str(profit) +"% \n" 
	content = content + " Return:" + str(fd['return']) + "% \n"
	content = content + " Profit:" + str(fd['profit']) + "\n"
	mail.send_mail(mailto, mailto, subject, content)


def notifyLoss(fund,fd):
	loss = fund.stopLoss * 100
	subject = fund.name + "  has reach Stop Loss"
	mailto = "rock.chiu@gmail.com"
	content = fund.name + " Stop Loss Rate:" + str(loss) +"% \n" 
	content = content + " Return:" + str(fd['return']) + "% \n"
	content = content + " Profit:" + str(fd['profit']) + "\n"
	mail.send_mail(mailto, mailto, subject, content)

	
		
def create(request):
	return render_to_response('fundata/create.html')
	

def processRequest(request,fund):
	name = request.POST['name']
	type = request.POST['type']
	startDate = request.POST['startDate']
	surcharge = request.POST['surcharge']
	stopLoss = request.POST['stopLoss']
	stopProfit = request.POST['stopProfit']
	currency = request.POST['currency']
	exchangeRate = request.POST['exchangeRate']
	dataSourceUrl = request.POST['dataSourceUrl']
	amount = request.POST['amount']
	comment = request.POST['comment']
	buyNetValue = request.POST['buyNetValue']
	buyCount = request.POST['buyCount']
	fund.name = name
	fund.type = type
	fund.startDate = datetime.strptime(startDate,"%Y-%m-%d").date()
	fund.surcharge = float(surcharge)
	fund.stopLoss = float(stopLoss)
	fund.currency = currency
	fund.exchangeRate = float(exchangeRate)
	fund.dataSourceUrl = dataSourceUrl
	fund.amount = float(amount)
	fund.comment = comment
	fund.buyNetValue = float(buyNetValue)
	fund.buyCount = float(buyCount)
	fund.stopProfit = float(stopProfit) 
	fund.put()
	

def save(request):
	name = request.POST['name']
	type = request.POST['type']
	fund = Fund(name=name,type=type)
	processRequest(request,fund)
	return render_to_response('fundata/show.html',{'fund':fund})
	
def delete(request,fund_id):
	fund = Fund.get(fund_id)
	fund.delete()
	return HttpResponseRedirect('/fundata/query/')
	
def edit(request,fund_id):
	fund = Fund.get(fund_id)	
	return render_to_response('fundata/edit.html',{'fund':fund})

def update(request,fund_id):
	fund = Fund.get(fund_id)
	processRequest(request,fund)
	return render_to_response('fundata/show.html',{'fund':fund})
